#!/usr/bin/env python

from FATFile import FATFile
import FuseStat

class FATDirectory:
   def __init__(self, image, fs, clusters):
      self.image = image
      self.fs = fs
      self.clusters = clusters
      self.name = "No Name"
      
   def getCluster(self):
      return self.clusters[0]
      
   def getName(self):
      return self.name
      
   def getParent(self):
         # very messy, should have a parent method of 
         c = self.clusters[0]
         # First cluster c contains the "." and ".." entries
         entries = self.image.getClusterEntries(c, self.fs)
         # want the ".." entry.
         parent = entries[1]
         if parent.name == ".." + 9 * " ":
            return parent.cluster()
         else:
            return None
            
   def __str__(self):
      return str(self.clusters)
      
   def getFiles(self):
   
      #
      #  Collect all entries together
      #
      entries = []
      for c in self.clusters:
         if c <> -1:
            entries.extend(self.image.getClusterEntries(c, self.fs))
      
      files = []
      start = 0
      for i in range(len(entries)):
         if not entries[i].isLongFileName():
            # Short file name, process all entries up to this point (should contain all LFN entries)
            f = FATFile(entries[start:i+1], self.fs)
            start = i + 1
            files.append(f)
            
      del(entries) # Pointers to the short file names still exist in the files variable.
            
      return files
            
   def getChildren(self):
      return self.getFiles()
      
   def getChild(self, name):
      for e in self.getChildren():
         if e.getName() == name:
            return e
      return None
      
   def getAttribs(self):
      fatde = self.getFiles()[0].fatde
      return FuseStat.FATStat(fatde)
      
   def isDirectory(self):
      return True
